package homework.no_6;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.UUID;

public class Spider {

    public static String getNewFileName(){
        String newFileName = UUID.randomUUID().toString().replaceAll("-","");
        return newFileName;
    }


    public static void getOnlineImageUrl(String urlStr){

        String workDir = System.getProperty("user.dir");
        String basePath = workDir+"\\images/";
        String fileName = getNewFileName()+".jpg";


        File file = new File(basePath,fileName);

        DataInputStream dis = null;
        DataOutputStream dos = null;

        try {
            URL url = new URL(urlStr);
            URLConnection connection = url.openConnection();
            dis = new DataInputStream(connection.getInputStream());
            dos = new DataOutputStream(new FileOutputStream(file));
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = dis.read(bytes)) != -1){
                dos.write(bytes,0,len);
                dos.flush();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (dis != null){
                try {
                    dis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (dos != null){
                try {
                    dos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void getHtmlResourceByUrl(String urlStr,String charset){
        BufferedReader bf = null;
        try {
            URL url = new URL(urlStr);
            URLConnection urlConnection = url.openConnection();

            bf = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), charset));
            String line = null;

            while ((line = bf.readLine()) != null){
                System.out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (bf != null){
                try {
                    bf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public static void main(String[] args) {

        /*String url = "https://www.jd.com/";     //字符流
        getHtmlResourceByUrl(url,"UTF-8");*/

        getOnlineImageUrl("http://img02.tooopen.com/images/20150227/tooopen_sy_81141126968.jpg");

    }
}
